<template>
  <div ref="container" class="container">
    <div class="header">
      <van-nav-bar
          fixed
          :title="chatItem.nickName"
          left-text="返回"
          left-arrow
          @click-left="onClickLeft"
      />
    </div>
    <div ref="chatbody" class="chat-body">
      <div v-for="item in chatItem.chat" :key="item.id">
        <div class="myself" v-if="item.myself===true">
          <div class="chatk">{{ item.content }}</div>
          <img class="imglogo" :src="myImg" alt="">
        </div>
        <div class="sheself" v-else>
          <img class="imglogo" :src="chatItem.sheImg" alt="">
          <div class="chatk">{{ item.content }}</div>
        </div>
      </div>
    </div>
    <div class="sendMessage">
      <div class="sendMessageSmall">
        <input style="height:30px;margin-right: 10px;border: none" type="text" v-model="text">
        <van-button @click="sendData" size="small" type="primary">发送</van-button>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: "chatList",
  data() {
    return {
      isHaveChart: null,//判断本地是否有聊天记录
      chatId: null,  //用户id
      chatAll: [],
      sheNickName: '奇怪猫', //她的昵称，默认奇怪猫
      sheName: '',   //她的用户名
      chatItem: {},   //此条聊天记录
      text: "",  //聊天内容
      socketUrl: "ws://"+this.$ws+":8887?myId=", // socket服务地址
      client: null, // webSocket实例
      myId: localStorage.getItem('user_id'),
      myImg:this.$baseUrl+localStorage.getItem('userimage'),
      data: "",
      myNickName: localStorage.getItem('nickname'),
      that:this
    }
  },
  created() {
    this.chatId = this.$route.params.id   //获取由商品页或者聊天列表传过来的用户id
    let data = localStorage.getItem('chatallinfo')   //获取本地所有聊天
    this.chatAll = JSON.parse(data)
    this.initChaing()      //初始化链接ws
    this.isHaveChart = this.chatAll.some((item) => {      //判断本地是否有此条聊天
      if (item.id === Number(this.chatId)) {
        this.chatItem = item
        this.chatItem.messageState=false  //修改已读状态
        return true
      }
    })
    if (this.isHaveChart == false) {   //如果本地没有聊天记录,根据id获取用户信息创建聊天
      this.$http.post('/users/getInfo', {sheId: this.chatId}).then((res) => {
        let result = res.data.sheInfo
        let ChartInfoMiddle = {
          id: result.id,
          sheName: result.username,
          nickName: result.nickname,
          messageState: false,
          sheImg: this.$baseUrl + result.userImage,
          chat: []
        }
        this.chatItem = ChartInfoMiddle  //创造此聊天
      })
    }
    this.$nextTick(()=>{
      this.$parent.$refs['bigBody'].scrollTop=99999
    })
  },
  watch: {
    chatItem: {
      handler() {
        this.$nextTick(() => {
          this.$parent.$refs['bigBody'].scrollTop=99999
        })
      },
      deep: true
    }
  },
  beforeDestroy() {
    //关闭ws连接
    this.client.close()
  },
  methods: {
    initChaing() {
      let that = this;
      if (window.WebSocket) {
        /* webSocket 连接服务器 */
        this.client = new WebSocket(this.socketUrl + this.myId);                     //这里要改为id

        /* 监听客户端连接 */
        this.client.onopen = function (ev) {
          if (ev.type === "open") {
            console.log("客户端连接socket服务");
          }
        };

        /* 监听服务端发送的消息 */
        this.client.onmessage = function (ev) {       //这里注意，在onmessage函数里面，this问题，所以用全局原型上属性要that
          let data = JSON.parse(ev.data);
          let localRecord=that.chatAll.some((item,idx)=>{

            if(item.id==data.myId){
              that.chatAll[idx].chat.push({myself: false, time: '', content:data.message})
              that.chatAll[idx].messageState=false
              return true
            }
          })

          if (localRecord == false) {   //如果本地没有聊天记录,根据id获取用户信息创建聊天
            that.$http.post('/users/getInfo', {sheId: data.myId}).then((res) => {
              let result = res.data.sheInfo
              let ChartInfoMiddle = {
                id: result.id,
                sheName: result.username,
                nickName: result.nickname,
                messageState: false,
                sheImg: that.$baseUrl + result.userImage,
                chat: [{myself:false, time:new Date().getTime(), content:data.message}]
              }
              this.chatItem = ChartInfoMiddle  //创造此聊天
            })
          }
          // that.chatingRecords.push(data); // 在线用户聊天                        这里要循环对对应的聊天插入信息
        };

        /* 监听服务端关闭 */
        this.client.onclose = function () {
          console.log("socket服务已关闭");
          that.client = null; // 客户端或者是服务端断开后，将webSocket实例清除
        };

        /* 监听服务端异常 */
        this.client.onerror = function () {
          if (!that.client) {
            console.log("socket服务连接失败");
          }
        };
      } else {
        alert("该浏览器不支持webSocket，请使用主流浏览器，如chrome");
      }
    },
    sendData() {
      let data = {
        myId: this.myId,
        sheId: this.chatItem.id,
        myImg: this.sheImg,
        myNickName: this.sheNickName,
        uid: new Date().getTime(),
        message: this.text,
        date: new Date(),
      };
    this.client.send(JSON.stringify(data));
      this.chatItem.chat.push({myself: true, time: '', content: this.text})
      this.text = "";

    },


    sendMessage() {
      this.chatItem.chat.push({myself: true, time: '', content: this.text})
      this.message = ''
      //调用对象发信息

      // this.chatAll.some((item)=>{
      //   if(item.id==this.chatId){
      //     item.chat.push({myself:true,time:'',content:this.message})
      //     this.message=''
      //   }
      // })

    },
    onClickLeft() {
      if (this.isHaveChart == false) {    //如果本地没有聊天直接插入聊天对象
        this.chatAll.push(this.chatItem)
        localStorage.setItem('chatallinfo', JSON.stringify(this.chatAll))
      } else {  //如果本地之前就有聊天，覆盖聊天
        this.chatAll.some((item,idx)=>{
          if(item.id==this.chatId){
            this.chatAll.splice(idx,1,this.chatItem)
            return true
          }
        })
        localStorage.setItem('chatallinfo',JSON.stringify(this.chatAll))

      }
      this.$router.back()
    }
  }
}
</script>
<style scoped lang="less">
html {
  .container {
    .header {
      height: 45px;
      text-align: center;
      line-height: 45px;
      background-color: #666666;
    }

    .chat-body {
      .sheself {
        text-align: left;

        .imglogo {
          display: inline-block;
          vertical-align: top;
          width: 45px;
          height: 45px;
          margin: 20px 10px;
          border-radius: 50%;
        }

        .chatk {
          max-width: 60%;
          vertical-align: top;
          margin: 35px 0 0 0;
          display: inline-block;
          background-color: #999999;
          min-height: 35px;
          border-radius: 5px;
          padding: 2px 7px;
          min-width: 30px;
        }
      }

      .myself {
        text-align: right;

        .imglogo {
          display: inline-block;
          vertical-align: top;
          width: 45px;
          height: 45px;
          margin: 20px 10px;
          border-radius: 50%;
        }

        .chatk {
          max-width: 60%;
          vertical-align: top;
          margin: 35px 0 0 0;
          display: inline-block;
          background-color: #999999;
          min-height: 35px;
          border-radius: 5px;
          min-width: 30px;
          padding: 2px 7px;
          text-align: left;
        }
      }
    }

    .sendMessage {
      .sendMessageSmall {
        width: 100%;
        background-color: #cccccc;
        position: fixed;
        bottom: 0;
        text-align: center;
      }
    }
  }
}
</style>
